#include <syslog.h>
#include <stdio.h>
#include <time.h>
#include <stdarg.h>
#include <unistd.h>
#include "log.h"


void write_log(int level, char *file, char *fmt, ...)
{
	const int syslogLevelMap[] = {LOG_DEBUG, LOG_WARNING, LOG_INFO, LOG_NOTICE};
	char msg[MAX_LOGMSG_LEN] = {0};
	char now[64] = {0};
	FILE *fp = NULL;
	time_t t = time(NULL);

	fp = (file==NULL)?stdout:fopen(file, "a");
	if(fp==NULL)
		return;

	va_list ap;

	va_start(ap, fmt);
	vsprintf(msg, fmt, ap);
	va_end(ap);

	strftime(now, sizeof(now), "%F %T", localtime((time_t*)&t));

	fprintf(fp, "[pid:%d]:%s %s\n", getpid(), now, msg);
	fflush(fp);

	if(file!=NULL)
		fclose(fp);

	syslog(syslogLevelMap[level], "%s", msg);
}
